package com.wuad.platformwuad.module.study.xml;

/**
 * @author wuaodi
 * 2024/10/23
 */
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * xml报文操作demo
 *
 * 联盟ESB对接
 * 接受报文--返回报文
 */
public class Demo {
    public static void main(String[] args) throws Exception{

        String resultStr = addIdsToXml("xml文本", "User");

        System.out.println(resultStr);
    }

    // 报文举例：
    /**
     * <?xml version=\"1.0\" encoding=\"UTF-8\"?>
     *     <Service>
     *         <Service_Header>
     *             <requester_id>0068</requester_id>
     *             <channel_id>96</channel_id>
     *             <version_id>01</version_id>
     *             <service_time>20161028192100</service_time>
     *             <start_timestamp>2016-10-28 19:21:00.021</start_timestamp>
     *             <branch_id>800777777</branch_id>
     *             <service_sn>1905120161028192100</service_sn>
     *             <service_id>00010000999900</service_id>
     *             <service_response/>
     *         </Service_Header>
     *         <Service_Body>
     *             <ext_attributes>
     *                 <INM-TELLER-ID>800777777D99</INM-TELLER-ID>
     *                 <SPR-DES></SPR-DES>
     *                 <OBJ-INST-ID>020305</OBJ-INST-ID>
     *                 <REQ_GLB_APPS_SYS_ID>0000068</REQ_GLB_APPS_SYS_ID>
     *                 <REQ_SUB_APPS_SYS_ID>0000</REQ_SUB_APPS_SYS_ID>
     *                 <INNER_DataProcPara>0,0,0</INNER_DataProcPara>
     *             </ext_attributes>
     *             <request>这里还有其他子集标签，代表请求参数<request/>
     *             <response/>这里还有其他子集标签，代表请求返回数据<response/>
     *         </Service_Body>
     *     </Service>
     */

    /**
     * 给报文指定节点标签添加属性
     *
     * 举例：
     * <response>           response>
     *   <INF_GRP>            <INF_GRP loop_num="1" p_type="G">
     *       <></>   >>>>>>>>     <></>
     *       <></>                <></>
     *   </INF_GRP>            </INF_GRP>
     * </response>           /response>
     * @param xml xml文本
     * @param model 根标签明名称
     * @return
     */
    public static String addIdsToXml(String xml, String model) {
        try {
            // 解析XML字符串为Document对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xml)));

            // 遍历所有元素并添加id属性，将星号改为执行元素名可获取指定元素标签
            NodeList nodes = document.getElementsByTagName("*");
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (!(node instanceof Element)) {
                    continue;
                }
                Element element = (Element) node;

                //根标签不需要设置id
                if (element.getTagName().equals(model)) {
                    continue;
                }

                // 设置id属性:属性名,属性值
                element.setAttribute("id", "123");
            }

            // 将修改后的Document对象转换回XML字符串
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(document), new StreamResult(writer));

            return writer.toString();
        } catch (Exception e) {
            // 处理异常，例如记录日志或抛出运行时异常
            throw new RuntimeException("Error processing XML", e);
        }
    }
}
